package com.paw.core.intercepter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.paw.common.context.UserContextHolder;
import com.paw.common.domain.Result;
import com.paw.common.enums.CommonResponseCodeEnum;
import com.paw.core.annotation.PreAuthorize;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author Rubble
 * @date 2021/9/3
 **/
@Slf4j
public class SecurityInterceptor implements HandlerInterceptor {

  @Override
  public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    if (!(handler instanceof HandlerMethod)) {
      return true;
    }
    HandlerMethod handlerMethod = (HandlerMethod) handler;
    PreAuthorize preAuthorize = handlerMethod.getMethodAnnotation(PreAuthorize.class);
    if (preAuthorize != null) {
      String value = preAuthorize.value();
      if (StrUtil.isEmpty(value)) {
        return true;
      }
      if (!UserContextHolder.hasUserContext()) {
        log.info("用户未登录");
        Result<Object> result = Result.generate(CommonResponseCodeEnum.UNAUTHORIZED);
        writeReturnJson(response, result);
        return false;
      }
      Set<String> permissions = UserContextHolder.getUser().getPermissions();
      if (CollUtil.isEmpty(permissions) || !permissions.contains(value)) {
        log.info("用户没有权限  userId: {} uri: {}",UserContextHolder.getUserId(),request.getRequestURI());
        Result<Object> result = Result.generate(CommonResponseCodeEnum.FORBIDDEN);
        writeReturnJson(response, result);
        return false;
      }
    }

    return true;
  }

  /**
   * 返回的json值
   *
   * @param response
   * @param result
   * @throws Exception
   */
  private void writeReturnJson (HttpServletResponse response, Result result) throws Exception {
    PrintWriter writer = null;
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=utf-8");
    try {
      writer = response.getWriter();
      writer.print(JSON.toJSONString(result));
    } catch (IOException e) {
    } finally {
      if (writer != null) {
        writer.close();
      }
    }
  }


}
